/*
 * Copyright (C), 2002-2016, 苏宁易购电子商务有限公司
 * FileName: ComponentApi.java
 * Author:   admin
 * Date:     2016年2月23日 下午4:04:57
 * Description: //模块目的、功能描述      
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名             修改时间            版本号                  描述
 */
package com.suning.app.snpaasadmin.api;

import com.suning.app.snpaasadmin.domain.ComponentDetail;
import com.suning.app.snpaasadmin.domain.ComponentInfo;
import com.suning.app.snpaasadmin.exception.BoshException;
import com.suning.app.snpaasadmin.util.Constants;
import com.suning.app.snpaasadmin.util.HttpClientResponse;
import com.suning.app.snpaasadmin.util.HttpClientUtil;
import com.suning.app.snpaasadmin.util.HttpStatusUtil;
import com.suning.app.snpaasadmin.util.JsonUtil;
import com.suning.app.snpaasadmin.util.StringUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.protocol.HttpContext;
import org.springframework.stereotype.Component;

/**
 * 〈一句话功能简述〉<br>
 * 〈功能详细描述〉
 *
 * @author admin
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Component
public class ComponentApi {

    public static Map<String, Object> getVms(HttpContext httpContext, HttpHost httpHost, String deployName)
            throws Exception {
        String urlPath = httpHost.toString() + "/deployments/" + deployName + "/vms?format=full";
        HttpClientResponse response = HttpClientUtil.doGet(urlPath, null, null, httpHost, httpContext);
        if (!HttpStatusUtil.isSuccessStatus(response.getStatus())) {
            String content = response.getBody();
            Map<String, Object> data = JsonUtil.convertJsonToMap(content);
            throw new BoshException(String.valueOf(response.getStatus()), data.get("description").toString());
        }
        String content = response.getBody();
        return JsonUtil.convertJsonToMap(content);
    }

    public static Map<String, Object> getTasks(HttpContext httpContext, HttpHost httpHost, Integer taskId)
            throws Exception {
        String urlPath = httpHost.toString() + "/tasks/" + taskId;
        HttpClientResponse response = HttpClientUtil.doGet(urlPath, null, null, httpHost, httpContext);
        if (!HttpStatusUtil.isSuccessStatus(response.getStatus())) {
            String content = response.getBody();
            Map<String, Object> data = JsonUtil.convertJsonToMap(content);
            throw new BoshException(String.valueOf(response.getStatus()), data.get("description").toString());
        }
        String content = response.getBody();
        return JsonUtil.convertJsonToMap(content);
    }

    @SuppressWarnings("unchecked")
    public static List<ComponentInfo> getComponents(HttpContext httpContext, HttpHost httpHost, Integer taskId)
            throws Exception {
        String urlPath = httpHost.toString() + "/tasks/" + taskId + "/output?type=result";
        HttpClientResponse response = HttpClientUtil.doGet(urlPath, null, null, httpHost, httpContext);
        if (!HttpStatusUtil.isSuccessStatus(response.getStatus())) {
            String content = response.getBody();
            Map<String, Object> data = JsonUtil.convertJsonToMap(content);
            throw new BoshException(String.valueOf(response.getStatus()), data.get("description").toString());
        }
        String content = response.getBody();
        String[] results = content.split("\n");
        List<ComponentInfo> infos = new ArrayList<ComponentInfo>();
        for (int i = 0; i < results.length; i++) {
            Map<String, Object> res = JsonUtil.convertJsonToMap(results[i]);
            String comName = (String) res.get("job_name");
            Integer state = 1;
            if ("running".equals(res.get("job_state").toString())) {
                state = 1;
            } else {
                state = 0;
            }
            String cpuUsage = ((Map<String, Object>) ((Map<String, Object>) res.get("vitals")).get("cpu")).get("sys")
                    .toString();
            String memUsage = ((Map<String, Object>) ((Map<String, Object>) res.get("vitals")).get("mem"))
                    .get("percent").toString();
            ComponentInfo comInfo = new ComponentInfo(comName, Double.valueOf(cpuUsage), Double.valueOf(memUsage),
                    Constants.DEFAULT_AMOUNT, state);
            infos.add(comInfo);
        }
        return infos;
    }

    @SuppressWarnings("unchecked")
    public static List<ComponentDetail> getComponentDetails(HttpContext httpContext, HttpHost httpHost, Integer taskId,
            String comName) throws Exception {
        String urlPath = httpHost.toString() + "/tasks/" + taskId + "/output?type=result";
        HttpClientResponse response = HttpClientUtil.doGet(urlPath, null, null, httpHost, httpContext);
        if (!HttpStatusUtil.isSuccessStatus(response.getStatus())) {
            String content = response.getBody();
            Map<String, Object> data = JsonUtil.convertJsonToMap(content);
            throw new BoshException(String.valueOf(response.getStatus()), data.get("description").toString());
        }
        String content = response.getBody();
        String[] results = content.split("\n");
        List<ComponentDetail> details = new ArrayList<>();
        for (int i = 0; i < results.length; i++) {
            Map<String, Object> res = JsonUtil.convertJsonToMap(results[i]);
            if (res.get("job_name")!= null
                    && comName.equals(res.get("job_name").toString())) {
                ComponentDetail comDetail = new ComponentDetail();
                comDetail.setIndex(Integer.valueOf(res.get("index").toString()));
                String ips = "";
                for (String ip : (List<String>) res.get("ips")) {
                    if (StringUtil.isNotEmpty(ips) && StringUtil.isNotNullString(ips)) {
                        ips = ip + "," + ips;
                    } else {
                        ips = ip;
                    }

                }
                comDetail.setIp(ips);
                String cpuUsage = ((Map<String, Object>) ((Map<String, Object>) res.get("vitals")).get("cpu"))
                        .get("sys").toString();
                comDetail.setCpuUsage(Double.valueOf(cpuUsage));
                List<String> cpuLoad = (List<String>) ((Map<String, Object>) res.get("vitals")).get("load");
                String loads = "";
                for (String load : cpuLoad) {
                    if (StringUtil.isNotEmpty(loads) && StringUtil.isNotNullString(loads)) {
                        loads = loads + "," + load.toString();
                    } else {
                        loads = load.toString();
                    }

                }
                comDetail.setCpuLoad(loads);
                String memoryUsage = ((Map<String, Object>) ((Map<String, Object>) res.get("vitals")).get("mem"))
                        .get("percent").toString();
                comDetail.setMemoryUsage(Double.valueOf(memoryUsage));

                Integer state = 1;
                if ("running".equals(res.get("job_state").toString())) {
                    state = 1;
                } else {
                    state = 0;
                }
                comDetail.setStatus(state);
                details.add(comDetail);
            }
        }
        return details;
    }

    public static String operateComponent(HttpContext httpContext, HttpHost httpHost, String deployName, String comName,
            Integer index, String operation, String filePath) throws Exception {
        String urlPath = httpHost.toString() + "/deployments/" + deployName + "/jobs/" + comName + "/" + index
                + "?state=" + operation;
        String data = DeploymentApi.getyml(filePath);
        CloseableHttpResponse response = HttpClientUtil.doPutWithComponent(urlPath, httpHost, httpContext, data);
        String location = "";
        try {
            if (response.getStatusLine().getStatusCode() == 302) {
                Header locationHeader = response.getFirstHeader("Location");
                if (locationHeader != null) {
                    location = locationHeader.getValue();
                    location = location.substring(location.lastIndexOf("/") + 1, location.length());
                }
            }
        } catch (Exception e) {
            throw e;
        }
        return location;
    }

}
